package com.usian.comment.service.impl

import com.usian.comment.feign.UserFeign
import com.usian.comment.service.CommentRepayService
import com.usian.model.comment.dtos.CommentRepayDto
import com.usian.model.comment.dtos.CommentRepayLikeDto
import com.usian.model.comment.dtos.CommentRepaySaveDto
import com.usian.model.comment.pojos.ApComment
import com.usian.model.comment.pojos.ApCommentRepay
import com.usian.model.comment.pojos.ApCommentRepayLike
import com.usian.model.comment.vo.ApCommentRepayVo
import com.usian.model.common.dtos.ResponseResult
import com.usian.model.common.enums.AppHttpCodeEnum
import com.usian.utils.threadlocal.AppThreadLocalUtils
import groovy.util.logging.Log4j
import org.springframework.beans.BeanUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Sort
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.findById
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.stereotype.Service
import java.util.*
import java.util.stream.Collectors

@Service
@Log4j
class CommentRepayServiceImpl : CommentRepayService {
    @Autowired
    lateinit var mongoTemplate: MongoTemplate
    @Autowired
    lateinit var userFeign: UserFeign


    /**
     *
     * @param dto
     * @return {@link null }
     * @Description: 加载评论回复列表
     * @author hyt
     * @creed: Talk is cheap,show me the code
     * @date 2022/4/7 19:22
     */

    override fun loadCommentRepay(dto: CommentRepayDto): ResponseResult<*> {
        //1.检查参数
        if (dto.commentId == null) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE)
        var size: Int = 10
        //2.按照文章id过滤，设置分页和排序
        var list = mongoTemplate.find(Query.query(Criteria.where("commentId").`is`(dto.commentId).and("createdTime").lt(dto.minDate)).limit(size).with(Sort.by(Sort.Direction.DESC, "createdTime")), ApCommentRepay::class.java)
        //3.是否登录
        var userId = AppThreadLocalUtils.getUser().id
        if (userId == null) ResponseResult.okResult(list)
        //3.2用户已登录,加载数据，需要判断当前用户点赞了哪些评论
        val idList = list.stream().map { x ->
            x.id
        }.collect(Collectors.toList());
        val quer = mongoTemplate.find(Query.query(Criteria.where("commentRepayId").`in`(idList).and("authorId").`is`(userId)), ApCommentRepayLike::class.java)
        val resultList: MutableList<ApCommentRepayVo> = mutableListOf()

        if (list != null && quer != null) {
            list.forEach {
                resultList.add(ApCommentRepayVo().apply {
                    BeanUtils.copyProperties(it, this)
                    for (apCommentLike in quer) {
                        if (apCommentLike.commentRepayId == it.id) {
                            this.operation = 0
                            break
                        }
                    }
                })
            }
            return ResponseResult.okResult(resultList)
        } else {
            return ResponseResult.okResult(list)
        }

    }

    /**
     *
     * @param dto
     * @return {@link null }
     * @Description: 保存回复评论
     * @author hyt
     * @creed: Talk is cheap,show me the code
     * @date 2022/4/7 19:22
     */
    override fun saveCommentRepay(dto: CommentRepaySaveDto): ResponseResult<*> {
        //1.检查参数
        if (dto.commentId == null) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE)
        if (dto.content != null && dto.content.length > 140) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "评论内容不能超过140字")
        //2.判读是否登录
        val userId = AppThreadLocalUtils.getUser().id
        if (userId == null) ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN)
        //3.安全过滤,自行实现
        //4.保存评论
        var apUser = userFeign.findUserById(userId)
        if (apUser == null) ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "当前登录信息有误")
        mongoTemplate.insert(ApCommentRepay().apply {
            authorId = apUser.id
            authorName = apUser.name
            content = dto.content
            commentId = dto.commentId
            createdTime = Date()
            updatedTime = Date()
            likes = 0
        })
        //更新评论回复数量
        val apComment = mongoTemplate.findById(dto.commentId, ApComment::class.java)
        apComment.reply = apComment.reply + 1
        mongoTemplate.save(apComment)
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS)


    }

    /**
     *
     * @param dto
     * @return {@link null }
     * @Description: 保存点赞回复内容
     * @author hyt
     * @creed: Talk is cheap,show me the code
     * @date 2022/4/7 19:22
     */
    override fun saveCommentRepayLike(dto: CommentRepayLikeDto): ResponseResult<*> {
        //1.检查参数
        if (dto.commentRepayId == null) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE)
        //2.判读是否登录
        var userId = AppThreadLocalUtils.getUser().id
        if (userId == null) ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN)
        //3.点赞操作
        var apCommentRepay = mongoTemplate.findById(dto.commentRepayId, ApCommentRepay::class.java)
        if (apCommentRepay != null && dto.operation == 0.toShort()){
            //更新评论的点赞数量
            apCommentRepay.likes = apCommentRepay.likes + 1
            mongoTemplate.save(apCommentRepay)
            //保存 APP评论信息点赞
            mongoTemplate.save(ApCommentRepayLike().apply {
                authorId=userId
                commentRepayId=apCommentRepay.id
                operation=dto.operation

            })
        }else if (apCommentRepay!=null&&dto.operation==1.toShort()){
            //4.取消点赞
            //更新评论的点赞数量
            apCommentRepay.likes=apCommentRepay.likes-1
            mongoTemplate.save(apCommentRepay)
            //更新APP评论信息点赞
            mongoTemplate.remove(Query.query(Criteria.where("authorId").`is`(userId).and("commentRepayId").`is`(apCommentRepay.id)),ApCommentRepayLike::class.java)

        }
        //5.数据返回
        return ResponseResult.okResult(mutableMapOf("likes" to apCommentRepay.likes))
    }


}